package com.wlj.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wlj.security.core.properties.LoginType;
import com.wlj.security.core.properties.WljSecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功处理器
 * 根据是否采用ajax的不同,需要登录成功后是重定向还是返回用户信息都是有可能的
 */
@Component("wljAuthenticationSuccessHandler")
public class WljAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WljSecurityProperties wljSecurityProperties;

    //Authentication封装了认证信息，包括请求的信息以及认证通过后的userDetails信息
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        logger.info("登录成功");

        if(LoginType.JSON.equals(wljSecurityProperties.getBrowser().getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }else{
            //如果不是json，则调用父类方法，跳转到原来触发认证的url
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
